package com.ehome.mobile.utils;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import android.os.StrictMode;

/**
 * Classe que faz a conexão com o web service (REST)
 * 
 * @author Silas M. Ferreira
 *
 */
public class RestSpring extends Thread {
	
	private Logger logger = Logger.getLogger(RestSpring.class);
	private RestTemplate restTemplate;
	private List<HttpMessageConverter<?>> messageConverters;
	private String url = "";
	
	public RestSpring() {
		try {
			this.restTemplate = new RestTemplate();
	
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
			StrictMode.setThreadPolicy(policy);
			
	        this.messageConverters = new ArrayList<HttpMessageConverter<?>>();
			this.messageConverters.add(new StringHttpMessageConverter());
			this.messageConverters.add(new GsonHttpMessageConverter());
			this.restTemplate.setMessageConverters(messageConverters);
	        this.restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
		} catch (Exception e) {
			logger.error("RestSpring()", e);
		}
	}
	
	public <T> T sendGET(Class<T> Clazz) {
		return restTemplate.getForObject(url, Clazz);
	}
	
	public <T> T sendPOST(Class<T> Clazz, Object object) {
		return restTemplate.postForObject(url, object, Clazz);
	}
	
	public void setUrl(String url) {
		this.url = url;
	}
}